#encoding: utf-8
module TableHelper
	include SpendsHelper

	attr_accessor :columns, :collection, :var
	
	#
	#
	class TableColumn
		attr_accessor :title, :value, :clazz, :header_class
		
		def initialize(title, value, clazz, header_class)
			@title = title
			@value = value
			@clazz = clazz
			@header_class = header_class
		end
	end
	
	class LinkColumn < TableColumn
		def initialize(clazz, header_clazz)
			super(nil, nil, clazz, header_clazz)
		end
	end
	
	#
	#
	class ShowColumn < LinkColumn
	end
	
	#
	#
	class EditColumn < LinkColumn
	end

	#
	#	
	class DestroyColumn < LinkColumn
	end

	#
	#
	def table(collection, var, options)
		return if collection.nil? or collection.empty? or var.nil?
		
		@columns = []
		@var = var
		@collection = collection

		yield(self)
		
		clazz = options[:class] unless options.nil?
		
		content_tag(:table, :class => clazz) do
			concat(generate_head)
			concat(generate_body)
		end
	end
	
	#
	#
	def column(title, value, options={})
		header_class 	= options[:header_class]
		clazz 				= options[:class]
	
		raise(ArgumentError, "title and value cannot be nil") if title.nil? or value.nil?
		
		@columns << TableColumn.new(title, value, clazz, header_class)
	end

	#
	#
	def show_column(options={})
		@columns << ShowColumn.new(options[:class], options[:header_class])
	end

	#
	#
	def edit_column(options={})
		@columns << EditColumn.new(options[:class], options[:header_class])
	end

	#
	#
	def destroy_column(options={})
		@columns << DestroyColumn.new(options[:class], options[:header_class])
	end
	
	private
	
	#
	#
	def generate_head
		head_row = content_tag(:tr) do
			@columns.collect do |column|
				content_tag(:th, column.title, :class => column.header_class)
			end.join.html_safe
		end
		
		content_tag(:thead, head_row)
	end

	#
	#
	def generate_body
		body_rows = @collection.collect do |e|

			content_tag(:tr) do
				@columns.collect do |column|

					#TODO refatorar
					if column.is_a? ShowColumn
						value = show_link(e)
					elsif column.is_a? EditColumn
						value = edit_link(e)
					elsif column.is_a? DestroyColumn
						value = destroy_link(e)
					else
						value = e.instance_eval(column.value)
					end

					content_tag(:td, value, :class => column.clazz)
				end.join.html_safe
			end

		end.join.html_safe

		content_tag(:tbody, body_rows)
	end
	
end
